<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入姓名" clearable v-model="userName" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="empList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="工号" prop="empCode"></el-table-column>
        <el-table-column label="姓名" prop="empName"></el-table-column>
        <el-table-column label="手机" prop="personalPhone"></el-table-column>
        <el-table-column label="邮箱" prop="personalEmail"></el-table-column>

        <el-table-column label="状态" prop="locked">
          <template slot-scope="scope">
            <span v-text="scope.row.locked==='0'?'正常':'锁定'"></span>
          </template>
        </el-table-column>

        <el-table-column label="角色">
          <template slot-scope="scope">{{ getRoleNames(scope.row.roles) }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="warning" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="removeUserById(scope.row.id,scope.row.locked==='0'?'1':'0')" v-text="scope.row.locked==='0'?'锁定':'解锁'"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 4 , 8, 16]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </el-card>
    <!--添加用戶-->
    <el-dialog title="添加用戶" :visible.sync="addDialogVisible" width="50%" :close-on-click-modal="false"
               @close="addUserFormClose">
      <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item label="用戶名" prop="userName">
          <el-input v-model="addUserForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword">
          <el-input v-model="addUserForm.userPassword" type="password"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="cellphone">
          <el-input v-model="addUserForm.cellphone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>

        <el-form-item label="角色" prop="userRoleList">
          <el-select v-model="userRoleList" multiple placeholder="请选择角色">
            <el-option :label="item.name" :value="item.id" v-for="item in roleList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否锁定" prop="locked">
          <el-select v-model="addUserForm.locked" placeholder="请选择是否锁定账户">
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUser">确 定</el-button>
        <el-button @click="cancelAddUser">取 消</el-button>
      </span>
    </el-dialog>


    <!--修改用戶  ~~~~-->
    <el-dialog
        title="修改用戶"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editUserFormClose"
        :close-on-click-modal="false"
    >
      <el-form
          :model="editUserForm"
          :rules="editUserFormRules"
          ref="editUserFormRef"
          label-width="100px"
          class="demo-ruleForm"
      >
        <el-form-item label="用户编号" prop="empCode">
          <el-input v-model="editUserForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="用戶名" prop="empName">
          <el-input v-model="editUserForm.empName"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="personalPhone">
          <el-input v-model="editUserForm.personalPhone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="personalEmail">
          <el-input v-model="editUserForm.personalEmail"></el-input>
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-select v-model="userRoleList" multiple placeholder="请选择角色">
            <el-option :label="item.name" :value="item.id" v-for="item in roleList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否锁定" prop="locked">
          <el-select v-model="editUserForm.locked" placeholder="请选择是否锁定账户">
            <el-option value="0" label="否"></el-option>
            <el-option value="1" label="是"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUser">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      editDialogVisible: false,
      swflag: false,
      pageNum: 1,
      pageSize: 4,
      empList: [],
      roleList: [], //系统中所有的角色
      userRoleList: [], //用户拥有的角色
      total: 9,
      userName: "",
      addDialogVisible: false,
      addUserForm: {
        userName: "",
        userCode: "",
        userPassword: "",
        locked: "",
        userRoleList: [],
        roleIds: '',
        email: "",
        cellphone: ""
      },
      editUserForm: {
        id: -1,
        empCode: "",
        empName: "",
        locked: 0,
        roleIds: "",
        personalPhone: "",
        personalEmail: ""
      },
      editUserFormRules: {
        // userCode: [
        //   { required: true, message: "請輸入工号", trigger: "blur" },
        //   { min: 6, max: 6, message: "工号必须是4个字符", trigger: "blur" }
        // ],
        // userName: [
        //   { required: true, message: "請輸入用戶名", trigger: "blur" },
        //   { min: 3, max: 8, message: "用戶名在3-8個字符之間", trigger: "blur" }
        // ],
        // locked: [{ required: true, message: "请选择账号状态", trigger: "blur" }]
      },
      addUserFormRules: {
        userName: [
          {required: true, message: "請輸入用戶名", trigger: "blur"},
          {min: 3, max: 8, message: "用戶名在3-8個字符之間", trigger: "blur"}
        ],
        userPassword: [
          {required: true, message: "請輸入密碼", trigger: "blur"},
          {min: 3, max: 8, message: "密碼在3-8個字符之間", trigger: "blur"}
        ],
        //userRoleList: [{type:"array", required: true, message: '請选择角色', trigger: 'change' }],
        locked: [{required: true, message: "请选择账号状态", trigger: "change"}],
        email: [
          {required: true, message: "請輸入邮箱", trigger: "blur"},
          {pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: "必须符合邮箱格式", trigger: "blur"}
        ],
        cellphone: [
          {required: true, message: "請輸入手机号", trigger: "blur"},
          {
            pattern: /^(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])\d{8}$/,
            message: "用戶名在3-8個字符之間",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    //锁定管理员
    removeUserById(eId,locked) {
      console.log(locked)
      let url = this.$HRMSUrl + "/employee/locked/"+eId+"/"+locked;
      this.$confirm('此操作将锁定该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //发送请求
        this.$axios.put(url)
            .then(res => {
              if (res.data.code === 200) {
                this.getUserList();
              } else {
                this.$message({
                  type: "error",
                  message: res.data.msg,
                  duration: 1000
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消锁定'
        });
      });
    },

    //显示修改框
    showEditDialog(row) {

      this.editDialogVisible = true;
      //当前的管理员对象数据赋值给 editUserForm
      this.editUserForm = row;
      //editUserForm 就拥有了 roles 属性
      console.log(this.editUserForm)
      //回显管理员拥有的角色
      if (row.roles.length > 0) {
        // alert(11)
        for (let r of row.roles) {
          //把角色的ID 盘放进 userRoleList数组中
          //alert(r.id);
          this.userRoleList.push(r.id)
        }
      }
      //把roles属性置空
      this.editUserForm.roles = [];
    },
    //关闭编辑对话框
    editUserFormClose() {
      this.$refs.editUserFormRef.resetFields();
      this.userRoleList = [];  //清除上一个管理的角色
      this.editUserForm.roleIds = ""; //清除选中的角色ID
    },

    //重点是保存修改id数据
    editUser() {
      this.editUserForm.roleIds = this.userRoleList.join(":");
      let url = this.$HRMSUrl + "employee/editManager";
      console.log(this.editUserForm)
      //依然带有 roles 属性  传递到后台  封装 roles 集合  就报错了
      this.$axios.put(url, this.editUserForm)
          .then(res => {
            if (res.data.code === 200) {
              this.editDialogVisible = false;
              this.getUserList();
            } else {
              this.$message({
                type: "error",
                message: res.data.msg,
                duration: 1000
              })
            }
          })
    },
    //添加新的管理员
    addUser() {
      this.$refs.addUserFormRef.validate(valid => {
        if (valid) {
          let url = this.$HRMSUrl + "/manager/add";
          //获取选中的角色id  赋值到 roleIds 属性上
          this.addUserForm.roleIds = this.userRoleList.join(":");
          console.log(this.addUserForm)
          //依然带有 roles 属性  传递到后台  封装 roles 集合  就报错了
          this.$axios.post(url, this.addUserForm)
              .then(res => {
                if (res.data.code === 200) {
                  this.addDialogVisible = false;
                  this.userRoleList = [];
                  this.addUserForm = {};
                  this.getUserList();
                } else {
                  this.$message({
                    type: "error",
                    message: res.data.msg,
                    duration: 1000
                  })
                }
              })
        } else {
          return false;
        }
      })
    },
    //取消添加管理员
    cancelAddUser() {
      this.addDialogVisible = false;
      this.userRoleList = [];
      this.addUserForm = {};
    },
    //关闭添加管理员的对话框
    addUserFormClose() {
      this.$refs.addUserFormRef.resetFields();
      this.userRoleList = [];
      this.addUserForm.deptId = "";
      this.addUserForm.roleIds = "";
    },

    //查询管理员用户
    getUserList() {
      let url = this.$HRMSUrl + "employee/listManager"
      this.$axios.get(url, {
        params: {
          empName: this.userName,
          currentPage: this.pageNum,
          pageSize: this.pageSize,
          pId:"",
          empType:"",

        }
      }).then(res => {
        if (res.data.code === 200) {
          console.log(res)
          this.empList = res.data.data.list;
          this.pageNum = res.data.data.pageNum;
          this.pageSize = res.data.data.pageSize;
          this.total = res.data.data.total;
        } else {
          this.$message({
            type: "error",
            message: res.data.msg,
            duration: 1000
          })
        }
      })
    },
    //查询所有的角色
    getRoleList() {
      let url = this.$HRMSUrl + "/role/getAll";
      this.$axios.get(url).then(res => {
        if (res.data.code === 200) {
          this.roleList = res.data.data;
        } else {
          this.$message({
            type: "error",
            message: res.data.msg,
            duration: 1000
          })
        }
      })
    },
    searchUser() {
      this.pageNum = 1;
      this.getUserList();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage;
      this.getUserList();
    },
    //把用户对象中包含的roleList其中的rolename转换为逗号分隔的字符串
    getRoleNames(arr) {
      if (!arr) return;
      let roleNameArr = new Array();
      for (let i = 0; i < arr.length; i++) {
        roleNameArr.push(arr[i].name);
      }
      return roleNameArr.join(",");
    },

    reloadData() {
      this.searchUser();
      this.getRoleList(); //用于添加和修改的时候 选择的
    }
  },
  created() {
    this.reloadData();
  }
};
</script>
<style lang="less" scoped>
</style>